package com.tanhua.sso.service;

import com.tanhua.sso.utils.SendSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsService {
    @Autowired
    private SendSmsUtils sendSmsUtils;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送验证码
     * @param phonenumbers
     * @return String
     */
    public String sendSms(String[] phonenumbers) {

        String code = sendSmsUtils.sendSms(phonenumbers);
        String redisKey = "SSO_SENDSMS_CODE" + phonenumbers[0];

        //先判断该手机号发送的验证码是否还未失效
        if (this.redisTemplate.hasKey(redisKey)) {
            return "上一次发送的验证码还未失效！";
        }
        if (StringUtils.isEmpty(code)) {
            return "发送短信验证码失败！";
        }
        //短信发送成功，将验证码保存到redis中，有效期为5分钟
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        return null;

    }
}
